package com.vieewer.btdemo.view.main.fragment

import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import com.lindroid.androidutilskt.extension.longToast
import com.vieewer.btdemo.R
import com.vieewer.btdemo.utils.XClickUtil
import com.vieewer.btdemo.view.info.SugonGlassesInfoManager
import kotlinx.android.synthetic.main.fragment_sys_info.view.*
import java.util.*



class SysInfoFragment : Fragment() {

    var mRootView : View? = null
    private var sensorManager: SensorManager? = null

    // 记录指南针图片转过的角度
    var currentDegree = 0f


    var mTimer : Timer ? = null
    var mTask: TimerTask ? = null



    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        mRootView = inflater.inflate(R.layout.fragment_sys_info, null)
        setInitViews()
        refreshUIView()
        return mRootView
    }



    private fun refreshUIView() {
        mRootView!!.txt_current_time.text = SugonGlassesInfoManager.instance.getCurrentTime()
        mRootView!!.txt_current_hour.text = SugonGlassesInfoManager.instance.getCurrentHour()

        val innerValue = SugonGlassesInfoManager.instance.getBatteryInfos()
        mRootView!!.txt_inner_battery.text = "$innerValue%"
        mRootView!!.sb_charge_small_battery.setProgress(innerValue)
        if (innerValue < 20 && XClickUtil.isValide(30*1000)) {
            longToast("眼镜内置电池电量已小于20%，请及时充电哦")
        }

        if (innerValue < 10 && XClickUtil.isValide(30*1000)) {
            longToast("眼镜内置电池电量已小于10%，请及时充电哦")
        }

        if (innerValue < 5 && XClickUtil.isValide(30*1000)) {
            longToast("眼镜内置电池电量已小于5%，请及时充电哦")
        }

        //Log.i("yjj", "SysInfoFragment 刷新内置电池电量  =" + innerValue)
    }



    private fun setInitViews() {

        SugonGlassesInfoManager.instance.setOnSecondBatteryChangeListener(object :
            SugonGlassesInfoManager.ISecondBatteryChange {
            override fun onSecondBatteryChange(battery: Int) {
                //刷新电量
                //Log.i("yjj" , "SysInfoFragment 刷新可更换电池电量  =$battery")
                mRootView!!.txt_left_time.text = "$battery%"
                mRootView!!.sb_charge_battery.setProgress(battery)

                if (battery < 20 && XClickUtil.isValide(30*1000)) {
                    longToast("眼镜大电池电量已小于20%，请及时更换电池哦")
                }

                if (battery < 10 && XClickUtil.isValide(30*1000)) {
                    longToast("眼镜大电池电量已小于10%，请及时更换电池哦")
                }

                if (battery < 5 && XClickUtil.isValide(30*1000)) {
                    longToast("眼镜大电池电量已小于5%，请及时更换电池哦")
                }

            }

        })



    }


    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)

        if (isVisibleToUser) {
            Log.i("yjj", "startTimerTask")
            startTimerTask()
        } else {
            Log.i("yjj", "cancelTimerTask")
            cancelTimerTask()
        }



    }





    fun startTimerTask() {

        if (mTimer == null) {
            mTimer = Timer()
        }

        if(mTimer != null && mTask != null) {
            mTask!!.cancel()
        }

        mTask = object : TimerTask() {
            override fun run() {
                if (activity != null) {
                    activity!!.runOnUiThread {
                        refreshUIView()
                    }
                }
            }
        }

        mTimer!!.schedule(mTask,0,5 *1000)

    }


    fun cancelTimerTask() {

        if(mTimer != null){
            mTask!!.cancel()
            mTimer!!.cancel()
            mTimer = null
            mTask = null
        }

    }




    val mEventListener = object : SensorEventListener {

        override fun onSensorChanged(sensorEvent: SensorEvent) {

            var angle = sensorEvent.values[0]

            var direction = SugonGlassesInfoManager.instance.getSensorDirection(angle)
            mRootView!!.txt_compass_direction.text = direction
            //Log.i("yjj", "direction =" + direction)


            // 创建旋转动画（反向转过degree度）
            val ra = RotateAnimation(
                currentDegree, -angle,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f
            )
            // 设置动画的持续时间
            ra.duration = 200
            // 运行动画
            //mRootView!!.img_compass.startAnimation(ra)
            currentDegree = -angle


        }

        override fun onAccuracyChanged(sensor: Sensor, i: Int) {

        }
    }





    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }



    private fun initView() {
        sensorManager = context!!.getSystemService(Context.SENSOR_SERVICE) as SensorManager
        sensorManager!!.registerListener(mEventListener,
            sensorManager!!.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME)
    }



    override fun onDestroy() {
        super.onDestroy()
        if (sensorManager != null) {
            sensorManager!!.unregisterListener(mEventListener)
        }
    }

    fun refreshBleStatus(isBleConnected: Boolean) {
        //img_ble.visibility = if (isBleConnected) View.VISIBLE else View.GONE

        if (activity != null) {
            activity!!.runOnUiThread {
                Log.i("yjj", "ble status change~~" + isBleConnected)
                if (isBleConnected) {
                    mRootView!!.img_ble.setImageResource(R.drawable.icon_connect_ble_h)
                } else {
                    mRootView!!.img_ble.setImageResource(R.drawable.icon_connect_ble_n)
                }
            }
        }

    }

    fun refreshWifiStatus(isWifiConnected: Boolean) {
        //img_wifi.visibility = if (isWifiConnected) View.VISIBLE else View.GONE
        if (isWifiConnected) {
            mRootView!!.img_wifi.setImageResource(R.drawable.icon_connect_wifi_h)
        } else {
            mRootView!!.img_wifi.setImageResource(R.drawable.icon_connect_wifi_n)
        }
    }



}